<?php 
$GLOBALS['Md'] = "TimeClock";
$GLOBALS['Pd'] = "B";
require_once($_SERVER['DOCUMENT_ROOT']."/defaultconf.mex");
print heade(); 
print body(); 
module($BSD['DB00']);
office_header($_SESSION[$SESSOF]);
include($GLOBALS['PAD']."Modules/Exchange/main.obj.php");
include($GLOBALS['PAD']."Modules/Exchange/nav.views.php");
print NavBack();

// Init Vars

	if (!isset($_POST['Currency'])) {
				$Currency = 2;
				} else {
				$Currency = $_POST['Currency'];
				}

		$previousDay = 0;
		$TotalDay = 0;
		$Count = 0;

if (isset($_POST['SaveOperations']) && isset($_POST['bpn_tax'])) {

// Save Profit Tax
	
	$CTaxProf = "INSERT INTO exchange_profit (profit_time, tax_bpn, operations_total,expenses_ref) VALUES ('{$GLOBALS['T']}','{$_POST['bpn_tax']}','0','1')";
	$TaxProf = $GLOBALS['CONN']->db_query($CTaxProf);
	
	$CallTaxProf = "SELECT ref FROM exchange_profit ORDER BY profit_time DESC LIMIT 0,1";
	$CallTax = $GLOBALS['CONN']->db_array($CallTaxProf);

if (!isset($_POST['profit_groups']) && isset($_POST['profit_day'])) { 

$profit_day = $_POST['profit_day'];
$n = count($profit_day);
 
    for ($s = 0; $s < $n; $s++)
   {
   	$currentDay = mktime(0,0,0,m($profit_day[$s]),d($profit_day[$s]),a($profit_day[$s]));
	$endDay = mktime(24,00,00,m($profit_day[$s]),d($profit_day[$s]),a($profit_day[$s]));

	$CCall = "SELECT * FROM exchange_operations WHERE operation_time BETWEEN '{$currentDay}' AND '{$endDay}' AND in_currency_ref = '{$_POST['Currency']}'
	AND profit_ref = '0'";
	$BCall = $GLOBALS['CONN']->db_array($CCall);
	
	for ($i = 1; $i <= $BCall[0]; $i++) { 
	$CBa = "UPDATE exchange_operations SET profit_ref = '{$CallTax[1]['ref']}' WHERE ref = '{$BCall[$i]['ref']}'";
	$Ba = $GLOBALS['CONN']->db_query($CBa);
	}
	$Count = $Count+$i;
}
}
 if (!isset($_POST['profit_operations']) && isset($_POST['profit_groups'])) { 
 
 $profit_groups = $_POST['profit_groups'];
 $profit_day_gr = $_POST['profit_day_gr'];
 $m = count($profit_groups);


     for ($s = 0; $s < $m; $s++)
   {
   
	$currentDay_gr = mktime(0,0,0,m($profit_day_gr[$s]),d($profit_day_gr[$s]),a($profit_day_gr[$s]));
	$endDay_gr = mktime(24,00,00,m($profit_day_gr[$s]),d($profit_day_gr[$s]),a($profit_day_gr[$s]));
	 
   	
	 
	$CCall2 = "SELECT * FROM exchange_operations WHERE operation_time BETWEEN '{$currentDay_gr}' AND '{$endDay_gr}' AND main_office_ref = '{$profit_groups[$s]}' AND in_currency_ref = '{$_POST['Currency']}'
	AND profit_ref = '0'";
	$BCall2 = $GLOBALS['CONN']->db_array($CCall2);
	
	for ($i = 1; $i <= $BCall2[0]; $i++) { 
	
	$CBa2 = "UPDATE exchange_operations SET profit_ref = '{$CallTax[1]['ref']}' WHERE ref = '{$BCall2[$i]['ref']}'";
	$Ba2 = $GLOBALS['CONN']->db_query($CBa2);
	}
	$Count = $Count+$i;
}
}
 if (isset($_POST['profit_operation'])) { $profit_operation = $_POST['profit_operation'];
 print $o = count($profit_operation);
 
     for ($s = 0; $s < $o; $s++)
   {
   	 
	$CCall3 = "SELECT * FROM exchange_operations WHERE ref = '{$profit_operation[$s]}'
	AND profit_ref = '0'";
	$BCall3 = $GLOBALS['CONN']->db_array($CCall3);
	
	for ($i = 1; $i <= $BCall3[0]; $i++) { 
	print $BCall3[$i]['ref']."<br>";
	$CBa3 = "UPDATE exchange_operations SET profit_ref = '{$CallTax[1]['ref']}' WHERE ref = '{$BCall3[$i]['ref']}'";
	$Ba3 = $GLOBALS['CONN']->db_query($CBa3);
	}
	$Count = $Count+$i;
}

}

// Update Profit Tax
	
	$CTaxProf = "UPDATE exchange_profit SET operations_total = '{$Count}' WHERE ref = '{$CallTax[1]['ref']}'";
	$TaxProf = $GLOBALS['CONN']->db_query($CTaxProf);
	
/*
	$QBPNRef = "INSERT INTO exchange_profit (profit_time,tax_bpn) VALUES ('{$_POST['bpn_time']}','{$_POST['bpn_tax']}'";
	$BPNRef = $GLOBALS['CONN']->db_query($QBPNRef);

	$Change = $_POST['profit_ref'];
	$Ref = $_POST['ref'];
	$C = count($Change);
	for ($c = 1; $c <= $C; $c++) {
	$CSave = "UPDATE exchange_operations SET profit_ref = '{$Change[$C]}' WHERE ref = '{$Ref[$C]}'";
	$GLOBALS['CONN']->db_query($CSave);
	}
	
	$QBPNRef = "UPDATE exchange_profit SET operations_total = '{$C}'";
	$BPNRef = $GLOBALS['CONN']->db_query($QBPNRef);
	
	
	$Msg->SEND_OPERATION = "Expedi��o Efectuada para as opera��es selecionadas.";
} else {
	$Msg->SEND_OPERATION = "Preencha todos os campos.";*/
}
?>

<table width="100%"  border="0" cellpadding="10">
	<tr>
    <td>Pesquisar OperaÇ&otilde;es      <?php echo mini_search();?></td>
  </tr>
  <?php if (isset($_GET['update']) && $_GET['update'] == "expenses") {?>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <?php } elseif(isset($_GET['update']) && $_GET['update'] == "profit") {?>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <?php } 
 
if (!isset($_POST['Search']) && !isset($_GET['update'])) { ?>
<form action="gest.php" method="post" enctype="multipart/form-data">
  <tr>
  <td colspan="2">Escolha uma moeda para consultar os totais</td>  </tr>
	  <tr><td colspan="2"><select name="Currency">
<?php
	$QCurrency = "SELECT * FROM main_settings_currency";
	$CurrencyE = $GLOBALS['CONN']->db_array($QCurrency);
	for ($C = 1; $C <= $CurrencyE[0]; $C++) { ?>
	
	<option value="<?php echo $CurrencyE[$C]['ref'];?>" <?php if ($Currency == $CurrencyE[$C]['ref']) { print "selected";} ?>><?php echo currency_output($CurrencyE[$C]['ref'],"icon");?></option>
	<?php } ?>
	</select>  <input type="submit" name="sel" value="Consultar"></td>  </tr>
  </tr>
<?php
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Default View
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  
		$QCallMain = "SELECT * FROM exchange_operations
		WHERE status = 'PAYED' 
		AND in_currency_ref = '{$Currency}'
		ORDER BY operation_time ASC";
	
	
		$QCallMain = $GLOBALS['CONN']->db_array($QCallMain);
			for ($m = 1; $m <= $QCallMain[0]; $m++) { 
			
			$currentDay = mktime(0,0,0,m($QCallMain[$m]['operation_time']),d($QCallMain[$m]['operation_time']),a($QCallMain[$m]['operation_time']));
			$endDay = mktime(24,00,00,m($QCallMain[$m]['operation_time']),d($QCallMain[$m]['operation_time']),a($QCallMain[$m]['operation_time']));

			if ($currentDay != $previousDay) {
			
			$QCallSub = "SELECT * FROM exchange_operations
			WHERE operation_time BETWEEN '{$currentDay}' AND '{$endDay}' AND
			status = 'PAYED'
			AND in_currency_ref = '{$Currency}'";
		if (!isset($_GET['Expand']) || $_GET['Expand'] == "Days") { 
			$QCallSub .= "LIMIT 0,1";
		} else {
			$QCallSub .= "GROUP BY main_office_ref ORDER BY main_office_ref ASC";
		}
			$CallSub = $GLOBALS['CONN']->db_array($QCallSub);
				for ($s = 1; $s <= $CallSub[0]; $s++) { 
					if ($s == 1) {
					
			$QTotals = "SELECT SUM(Amount) AS Amount FROM exchange_operations
			WHERE operation_time BETWEEN '{$currentDay}' AND '{$endDay}'
			AND status = 'PAYED'
			AND (profit_ref = '0' OR profit_ref = '')
			AND in_currency_ref = '{$Currency}'";
			$Total5 = $GLOBALS['CONN']->db_array($QTotals);
			$Total = $Total5[1]['Amount'];

					
					print "<tr bgcolor=\"#C1D0E1\">";
					print "<td colspan=\"7\"><b>".date_output($currentDay)." | <a href=\"gest.php?Expand=Groups&ID={$currentDay}&COND={$endDay}\">Expandir Dia</a> - <a href=\"gest.php?Expand=Days&ID={$currentDay}&COND={$endDay}\">Impludir Dia</a> | Total: ";
					print number_format($Total,2).currency_output($Currency,"icon")."</b></td>";
					print "<td><input name=\"profit_day[]\" type=\"checkbox\" value=\"{$currentDay}\"></td>";
					print "</tr>";
				
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// View Groups
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
				
					} 
					
		if (isset($_GET['Expand']) && $_GET['Expand'] == "Groups" || isset($_GET['Expand']) && $_GET['Expand'] == "Operations") {
					print "<tr bgcolor=\"#F2F2F2\"><td colspan=\"8\"><b>";
					print "Opera��es ";
					
					$FFunc = "SELECT * FROM main_offices
					WHERE ref = '{$CallSub[$s]['main_office_ref']}'";
					$Func = $GLOBALS['CONN']->db_array($FFunc);
					print $Func[1]['office_number']." ".$Func[1]['name'];
					
			$QTotalOffs = "SELECT SUM(Amount) AS Amount FROM exchange_operations
			WHERE operation_time BETWEEN '{$currentDay}' AND '{$endDay}'
			AND status = 'PAYED'
			AND (profit_ref = '0' OR profit_ref = '')
			AND in_currency_ref = '{$Currency}'
			AND main_office_ref = '{$CallSub[$s]['main_office_ref']}'";
			$TotalOff5 = $GLOBALS['CONN']->db_array($QTotalOffs);
			$TotalOff = $TotalOff5[1]['Amount'];
					
					print " | <a href=\"gest.php?Expand=Operations\">Expandir Categoria</a> - <a href=\"gest.php?Expand=Groups\">Contrair Categoria</a> | Total: ".number_format($TotalOff,2).currency_output($Currency,"icon")."</b></td>";
					print "<td><input name=\"profit_day_gr[]\" type=\"hidden\" value=\"{$currentDay}\"><input name=\"profit_groups[]\" type=\"checkbox\" value=\"{$CallSub[$s]['main_office_ref']}\"></td>";
					print "</tr>";
					
	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// View Operations
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	if (isset($_GET['Expand']) && $_GET['Expand'] == "Operations") {
					
					$QCallSubSub = "SELECT * FROM exchange_operations
					WHERE operation_time BETWEEN '{$currentDay}' AND '{$endDay}' 
					AND status = 'PAYED' 
					AND main_office_ref = '{$CallSub[$s]['main_office_ref']}'
					AND in_currency_ref = '{$Currency}'";
					$CallSubSub = $GLOBALS['CONN']->db_array($QCallSubSub);
						for ($z = 1; $z <= $CallSubSub[0]; $z++) {
						print "<tr bgcolor=\"#F5F1D8\">";
						print "<td colspan=\"7\"><b>".$CallSubSub[$z]['ref']." | Valor da Opera��o: ".number_format($CallSubSub[$z]['Amount']).currency_output($CallSubSub[$z]['in_currency_ref'],"icon")."</b> | Comprada a ".$CallSubSub[$z]['tax1']."</td>";
						print "<td>";
						if ($CallSubSub[$z]['profit_ref'] == '0' || $CallSubSub[$z]['ref'] == '') { print "<input name=\"profit_operation[]\" type=\"checkbox\" value=\"{$CallSubSub[$z]['ref']}\">";
						} else {
					$QProfit = "SELECT * FROM exchange_profit WHERE ref = '{$CallSubSub[$z]['profit_ref']}'";
					$Profit = $GLOBALS['CONN']->db_array($QProfit);
						print $Profit[1]['tax_bpn'];
						$Average = round(($Profit[1]['tax_bpn']/$CallSubSub[$z]['tax1']-1)*100,4);
						print " | ".$Average."%";
						}
						print "</td>";
						print "</tr>";
						}
	}
// END View Operations ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

				}
			}
// END View Groups ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			$previousDay = $currentDay;
			}
		}
// END Default View ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
?>
<?php /*
   <tr>
    <td>Opera��es do dia
      <table width="100%"  border="0" cellpadding="5" cellspacing="2">
          <tr bgcolor="#99CCCC" align="center">
            <td bgcolor="#99CCCC" width="20%">Loja</td>
            <td>Recibo</td>
            <td width="20%">Data</td>
            <td width="20%">Cliente</td>
			<td>Taxa</td>
            <td width="15%">Valor Recebido</td>
            <td width="15%">Valor Entregue</td>
            <td width="5%">Estado</td>
			<td width="10%">Lucro</td>
			<td width="10%">Despesas</td>
			<td width="5%">Malote</td>
          </tr>
 <?php  
	$QCallMain = "SELECT * FROM exchange_operations";
	$CallMain = $GLOBALS['CONN']->db_array($QCallMain);
	for ($m = 1; $m <= $CallMain[0]; $m++) { 
	?>
          <tr bgcolor="#F2F2F2"<?php if ($CallMain[$m]['status'] == 'CANCELED') {?> style="color:#FF0000;"<?php } ?>>
            <td>
	<?php
	$QCallSub = "SELECT * FROM main_offices WHERE ref = '{$CallMain[$m]['main_office_ref']}'";
	$CallSub = $GLOBALS['CONN']->db_array($QCallSub);
	for ($s = 1; $s <= $CallSub[0]; $s++) {
	print $CallSub[$s]['name'];
	} ?>
	</td>
            <td align="right"><?php echo $CallMain[$m]['control_ref'];?><input type="hidden" name="ref[]" value="<?php echo $CallMain[$m]['ref'];?>"></td>
            <td><?php echo time_output($CallMain[$m]['operation_time']);?></td>
                 <td width="20%">
				 
	<?php
	$QCallSub = "SELECT * FROM main_clients WHERE ref = '{$CallMain[$m]['main_clients_ref']}'";
	$CallSub = $GLOBALS['CONN']->db_array($QCallSub);
	for ($s = 1; $s <= $CallSub[0]; $s++) {
	print $CallSub[$s]['name']." ".$CallSub[$s]['name_middle']." ".$CallSub[$s]['name_last'];
	} ?></td>
                 <td><?php echo $CallMain[$m]['tax1'];?></td>
                 <td align="right"><?php echo $CallMain[$m]['Amount']." ".currency_output($CallMain[$m]['in_currency_ref'],'icon');?></td>
				 <td align="right"><?php echo $CallMain[$m]['acerto']." ".currency_output($CallMain[$m]['out_currency_ref'],'icon');?></td>
            <td>
			<?php 
			if ($CallMain[$m]['status'] == 'PAYED') {
			 print "Pago"; 
			} elseif ($CallMain[$m]['status'] == 'CANCELED') {
			 print "Anulada";
			 } ?>
			 </td>
			 <td><?php if ($CallMain[$m]['status'] == 'PAYED') { 
			 	if ($CallMain[$m]['profit_ref'] == '0') { ?><input name="profit_ref[]" type="checkbox" value="<?php echo $CallMain[$m]['profit_ref'];?>"><?php }
				else { print $CallMain[$m]['profit_ref'];}
				} ?></td>
			 <td><?php if ($CallMain[$m]['status'] == 'PAYED') {?><input name="expenses_ref[]" type="checkbox" value="<?php echo $CallMain[$m]['expenses_ref'];?>"><?php } ?></td>
			 <td><?php if ($CallMain[$m]['status'] == 'PAYED') {?><input name="malote_ref[]" type="text" value="<?php echo $CallMain[$m]['malote'];?>" size="5" maxlength="10"><?php } ?></td>
         </tr>
		 <?php } ?>
      </table></td>
  </tr>
  <?php } if (isset($_POST['Search'])) { ?>
  <tr>
    <td>Resultados da Pesquisa para <b></b>
      <table width="100%"  border="0" cellpadding="2" cellspacing="3">
      <tr bgcolor="#99CCCC">
        <td>Data</td>
        <td>Moedas</td>
        <td>Compra</td>
        <td>Venda</td>
      </tr>
<?php 
	$QCall = "SELECT * FROM exchange_operations";
	$Call = $GLOBALS['CONN']->db_array($QCall);
	for ($i = 1; $i = $Call[0]; $i++) { ?>

      <tr bgcolor="#F2F2F2">
        <td width="20%" rowspan="2"><?php echo time_output($Call[$i]['rate_time']);?></td>
        <td><?php echo $Call[$i]['currency1'];?></td>
        <td bgcolor="#F2F2F2"><?php echo $Call[$i]['buy1'];?></td>
        <td><?php echo $Call[$i]['sell1'];?></td>
      </tr>
      <tr bgcolor="#F2F2F2">
        <td width="40%"><?php echo $Call[$i]['currency1'];?></td>
        <td width="20%" bgcolor="#F2F2F2"><?php echo $Call[$i]['buy2'];?></td>
        <td width="20%"><?php echo $Call[$i]['sell2'];?></td>
      </tr>
	  <?php }*/ ?>
    </table></td>
  </tr>
 
   <table width="100%"  border="0" cellpadding="6" cellspacing="3">
  <tr bgcolor="#009999">
<td colspan="2">Taxa de Lucro BPN | Venda de Opera��es</td>
</tr>
<tr bgcolor="#F2F2F2">
<td>Data: <?php echo form_input_time("bpn_time",$GLOBALS['T']);?></td><td>Taxa: <input name="bpn_tax" type="text" size="4" value="0.0000" maxlength="10"></td>
</tr>
	<tr>
	<td><input name="SaveOperations" type="submit" value="Vender a esta Taxa"></td>
	</tr>
</form> 
<?php } ?>
</table>
</table>

<?php print footer(); ?>